<template>
	<view class="phone-login-page">
		<div v-if="loading" class="loading">
			<img src="https://cdndoc.bj.xdf.cn/student/images/loading.gif" alt="" />
		</div>
        <div v-if="!loading">
            <!-- 获取手机验证码 -->
            <div v-if="!isSendMsg" class="page-content">
                <h2 class="big-text bottom-line">短信验证登录</h2>
                <div class="thin-text">未注册的手机号验证通过后将自动创建账号 </div>
                <div class="input-content">
                    <div class="input-item name_row" style="display: flex;">
                        <div style="position:relative; flex: 1;">
                            <input v-model="mobile" type="number" class="phone-number" maxlength="11" @input="inputPhone($event)" @blur="phoneBlue($event)" placeholder="请输入手机号" />
                            <div v-if="errorMobile" class="tit_text" ref="name_tit">手机号有误， 请重新输入</div>
                        </div>
                        <div style="width: 80rpx;" v-if="mobile">
                            <view style="background-color: #F5F5F5; width: 80rpx; height: 96rpx;z-index: 20; text-align: center; line-height: 96rpx;" class="clear_btn iconfont icon-close" ref="clearName" @click="clearMobile" ></view>
                        </div>
                    </div>
                    <div class="input-code-item input-item name_row">
                        <div class="short-input" style="position:relative;">
                            <input v-model="imageCode" maxlength="10" class="phone-number" placeholder="请输入右侧验证码" />
                            <div v-if="errorCodeTip" class="tit_text" ref="name_tit">{{ errorCodeText }}</div>
                        </div>
                        <div class="code-panel">
                            <div class="code-img">
                                <image :src="codeImg"></image>
                            </div>
                            <label class="code-text" @click="getImageCode">换一换</label>
                        </div>
                    </div>
                </div>
                <div class="code-btn" :class="{'code-btn-active': checkValid }" @click="sendCode">
                    获取短信验证码
                </div>
                <view class="protocol">
                	<view class="bottom-view">
                        <uni-icons class="radio-icon" v-if="!isReadProtocol" color="#C2C2C2" type="circle" size="14" @click="isReadProtocol = !isReadProtocol"></uni-icons>
                        <uni-icons class="radio-icon" v-if="isReadProtocol" color="#428AF6" type="checkbox-filled" size="14" @click="isReadProtocol = !isReadProtocol"></uni-icons>
                		<text>阅读并同意</text><text class="blue-text" @click="viewUserProtocol">《用户协议》</text>和<text class="blue-text" @click="viewProtocol">《隐私协议》</text>
                	</view>
                </view>
            </div>
            <!-- 输入短信验证码区域 -->
            <div v-if="isSendMsg" class="page-content">
                <div class="big-text">请输入验证码</div>
                <div class="code-flex">
                    <div class="thin-text">短信验证码已发送至<label style="color: #333333; padding-left: 6rpx;">{{ mobile | formattedNumber }}</label></div>
                    <div v-if="sendTime > 0" class="thin-text color-blue"><label>{{ sendTime }}</label>s</div>
                    <div v-if="sendTime <= 0" class="thin-text color-blue" @click="reSendMsg">重新发送</div>
                </div>
                <div class="input-list">
                    <CodeBox ref="codeBox" v-if="isSendMsg" @ok="doCheckCode"></CodeBox>
                </div>
                <!-- 测试环境提示验证码区域 -->
                <div v-if="testCode && isTest" style="padding: 30rpx 0;">
                    {{ testCode }}
                </div>
            </div>
        </div>
	</view>
</template>

<script>
    import {
        apiBindingLogin,
        apiGetVerificationImageCode,
        apiSendVerificationMessageCode,
        apiLoginBymobile
    } from '@/api/user/user.js'
    import { generateMixed } from '@/common/util/util.js'
    import {
        mapActions
    } from "vuex"
    import CodeBox from './components/CodeBox.vue'
	export default {
        name: 'PhoneLogin',
        components: {
            CodeBox
        },
		data() {
			return {
                isTest: false,
                testCode: '',
                isSendMsg: false,
                randomKey: '',
				loading: false,
                isReadProtocol: false,
                mobile: '',
                errorMobile: false,
                errorCodeTip: false,
                errorCodeText: '验证码错误',
                sendTime: 60,
                bindInfo: {
                    banding: false,
                    mobile: null,
                    openId: "",
                    studentCode: null,
                    studentName: null,
                    token: null,
                    unionId: ""
                },
                codeImg: '',
                imageCode: '',
                msgCode: ''
			}
		},
		onLoad(options) {
            if(process.env.NODE_ENV == 'development'){//h5分享页的生产和测试环境地址区分
                this.isTest = true
            }
            this.randomKey = new Date().getTime() + '' + generateMixed(8)   // 用户获取图形验证码的随机数
            uni.removeStorageSync('Access-Token');
            let _this = this
            // #ifdef MP-WEIXIN
            wx.login({
                success(res) {
                    if (res.code) {
                        // console.log('wxcode:'+ res.code)
                        //发起网络请求
                        _this.bindingEnhance(res)
                    }
                }
            })
            // #endif
		},
		onShow() {
            this.getImageCode()
            for (let i=0; i<this.codeLength; i++) {
                const item = {
                    value: '',
                    focus: false
                }
                if (i === 0) {
                    item.focus = true
                }
                this.boxList.push(Object.assign({},item))
            }
		},
        computed: {
            checkValid() {
                return (this.mobile.length === 11 && this.errorMobile === false && this.imageCode.length === 4)
            }
        },
        filters: {
            formattedNumber: function(value) {
                if (value) {
                    var formattedNumber = value.replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3");
                    return formattedNumber
                }
            }
        },
		methods: {
            ...mapActions(["doLogin"]),
            // 图形验证吗
            getImageCode() {
                apiGetVerificationImageCode({
                    randomKey: this.randomKey
                }).then(res => {
                    this.codeImg = res.data.src
                    this.errorCodeTip = false
                    this.imageCode = ''
                })
            },
            // 查看隐私协议
            viewProtocol() {
            	uni.navigateTo({
            		url: '/pages/login/protocol'
            	})
            },
            viewUserProtocol() {
                uni.navigateTo({
                	url: '/pages/login/userProtocol'
                })
            },
            bindingEnhance(res) {
                let _this = this
                apiBindingLogin({
                    code: res.code
                }).then(res => {
                    if (res.code === 200) {
                        this.bindInfo = res.data
                    } else {
                        this.loading = true
                    }
                }).catch(err => {
                    this.loading = true
                })
            },
            // 输入手机号的事件
            inputPhone(e) {
                // if(e.detail.value.length==11) {
                //     if (!(/^(((1[3,4,5,6,7,8,9][0-9]{1}))+\d{8})$/).test(this.mobile.trim())) {
                //     	this.errorMobile = true
                //     } else {
                //     	this.errorMobile = false
                //     }
                // }
            },
            // 节流方法
            throttleMethod: function (fn, delay) {
              if (!this.throttledFunction) {
                this.throttledFunction = setTimeout(function () {
                  fn(); // 调用传入的方法
                  this.throttledFunction = null; // 清空节流方法
                }, delay);
              }
            },
            // 输入手机号 失去焦点
            phoneBlue(e) {
                if(e.detail.value.length>0) {
                    if (!(/^(((1[3,4,5,6,7,8,9][0-9]{1}))+\d{8})$/).test(this.mobile.trim())) {
                        this.errorMobile = true
                    } else {
                        this.errorMobile = false
                    }
                } else {
                    this.errorMobile = false
                }
            },
            clearMobile() {
            	
            	this.mobile = ''
                setTimeout(() => {
                    this.errorMobile = false
                }, 150)
            },
            // 发送验证码
            sendCode() {
                if (this.checkValid) {
                    if (!this.isReadProtocol) {
                        uni.showToast({
                            title: "请先勾选阅读并同意《用户协议》和《隐私协议》",
                            duration: 2000,
                            icon: 'none'
                        })
                    } else {
                        apiSendVerificationMessageCode({
                            mobile: this.mobile,
                            randomKey: this.randomKey,
                            imageCode: this.imageCode
                        }).then(res => {
                            
                            if (res.code === 200) {
                                uni.showToast({
                                    title: '短信验证码发送成功！',
                                    icon: 'none'
                                })
                                this.countdown()
                                this.testCode = res.data
                                this.isSendMsg = true
                            }
                        }).catch(res => {
                            if (res.code === 500) {
                                if (res.msg === '验证码已过期') {
                                    uni.showToast({
                                        title: res.msg + ' ',
                                        duration: 2000,
                                        icon: 'none'
                                    })
                                    this.getImageCode()
                                } if (res.msg === '获取验证码过于频繁，请1分钟后尝试') {
                                    uni.showToast({
                                        title: res.msg + ' ',
                                        duration: 2000,
                                        icon: 'none'
                                    })
                                    this.getImageCode()
                                } else {
                                    this.errorCodeTip = true
                                    this.errorCodeText = res.msg
                                }
                            }
                        })
                    }
                }
            },
            // 控制短信倒计时
            countdown() {
                this.sendTime = 59
                let interVal = setInterval(() => {
                    if (this.sendTime > 0) {
                        this.sendTime--
                    } else {
                        clearInterval(interVal)
                    }
                }, 1000)
            },
            // 重新发送短信
            reSendMsg() {
                apiSendVerificationMessageCode({
                    mobile: this.mobile,
                }).then(res => {
                    if (res.code === 200) {
                        uni.showToast({
                            title: '短信验证码发送成功！',
                            icon: 'none'
                        })
                        this.sendTime = 60
                        this.countdown()
                        this.testCode = res.data
                        this.isSendMsg = true
                    }
                })
            },
            loginByPhone() {
                apiLoginBymobile({
                    mobile: this.mobile,
                    verificationCode: this.msgCode,
                    openId: this.bindInfo.openId,
                    unionId: this.bindInfo.unionId
                }).then(res => {
                    if (res.code === 200) {
                        uni.showToast({
                            icon: 'none',
                            title: '验证成功！'
                        })
                        setTimeout(() => {
                            // 往storage放数据
                            this.doLogin(res.data)
                            this.toPage()
                        }, 1000)
                    } else {
                        this.$refs.codeBox.initCodeBox()
                        uni.showToast({
                            title: res.msg + '',
                            icon: 'none'
                        })
                    }
                })
            },
            toPage() {
                if (uni.getStorageSync('origin')) {
                    let url = uni.getStorageSync('origin')
                    uni.setStorageSync('origin', '')
                    uni.redirectTo({
                        url: url
                    })
                } else {
                    uni.switchTab({
                        url: "/pages/index/index"
                    })
                }
            },
            doCheckCode(val) {
                this.msgCode = val
                this.loginByPhone()
            }
		}
	}
</script>

<style scoped lang="scss">
    .loading {
		height: 100vh;
		width: 100%;
		background-color: #FFFFFF;
		display: flex;
		position: fixed;
		left: 0;
		top: 0;
		align-items: center;
		justify-content: center;

		img {
			width: 150px;
			height: 150px;
		}
	}
    .page-content {
        padding: 124rpx 57rpx;
    }
    .big-text {
        font-weight: bold;
        font-size: 42rpx;
        color: #333333;
        position: relative;
    }
    .bottom-line::after {
            position: absolute;
            content: "";
            bottom: 0;
            left: 0;
            top: 45rpx;
            width: 136rpx;
            height: 17rpx;
            background: linear-gradient(-90deg, #E4F8FF 0%, #448CF7 99%);
            border-radius: 12rpx 12rpx 2rpx 2rpx;
            z-index: -1;
    }
    .thin-text {
        padding-top: 20rpx;
        color: #999999;
        font-size: 24rpx;
        font-weight: 400;
    }
    .input-content {
        padding-top: 80rpx;
    }
    .name_row {
        .clear_btn {
            font-size: 32rpx;
            color: #cccccc;
            z-index: 2;
            border-radius: 0 8rpx 8rpx 0;
        }
    
        .tit_text {
            position: absolute;
            left: 0;
            top: 100rpx;
            font-size: 22rpx;
            color: #FF2525;
        }
    }
    .input-item {
        margin-bottom: 50rpx;
        .phone-number {
            border-radius: 8rpx;
            background-color: #F5F5F5;
            height: 96rpx;
            line-height: 96rpx;
            padding-left: 28rpx;
            font-size: 28rpx;
            color: #333333;
        }
    }
    
    .input-code-item {
        display: flex;
        justify-content: space-between;
        .short-input {
            flex: 1;
        }
        .code-panel {
            width: 241rpx;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            .code-text {
                color: #397EF5;
                font-size: 24rpx;
                padding-left: 18rpx;
            }
            .code-img {
                width: 128rpx;
                height: 68rpx;
                padding-left: 23rpx;
            }
            .code-img image {
                width: 100%;
                height: 100%;
            }
        }
    }
    .code-btn {
        margin-top: 70rpx;
        height: 82rpx;
        background: #f5f5f5;
        border-radius: 41rpx;
        font-size: 28rpx;
        color: #999999;
        line-height: 82rpx;
        text-align: center;
    }
    .code-btn-active {
        background: #428AF6;
        color: #ffffff;
    }
    .protocol {
        margin-top: 30rpx;
    	width: 100%;
    	text-align: center;
    }
    .bottom-view {
    	display: flex;
    	align-items: center;
    	justify-content: center;
    	font-size: 24rpx;
    	height: 30px;
    	line-height: 30px;
    	color: #999999;
    	.blue-text {
    		color: #428AF6;
    	}
    }
    .radio-icon {
        font-size: 24rpx;
        color: #428AF6;
        margin-right: 10rpx;
    }
    .code-flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .color-blue {
        color: #428AF6;
    }
    .input-list {
        margin-top: 72rpx;
    }
    
</style>
